﻿using Microsoft.Extensions.Hosting;
using System.Diagnostics;
using System.Text;

namespace ToPDF.Data
{
    public class PdfHelp
    {

        public string PdfContentType = "application/pdf";

        private readonly IWebHostEnvironment _hostEnvironment;
        public PdfHelp(IWebHostEnvironment hostEnvironment)
        {
            _hostEnvironment = hostEnvironment;
        }

        public string GetWkhtmltopdfExePath()
        {
            string exePath = Path.Combine(_hostEnvironment.WebRootPath, PDF.WkhtmltopdfExePath);
            return exePath;
        }

        public bool IsWkhtmltopdfInstalled()
        {
            bool isInstalled = false;
            string exePath = GetWkhtmltopdfExePath();
            if (File.Exists(exePath))
            {
                isInstalled = true;
            }
            return isInstalled;
        }
        //将内容写入html 
        public async Task<string> WriteHtmlToFile(string html)
        {
            string isWritten;
            try
            {
                isWritten = Path.Combine(_hostEnvironment.ContentRootPath, "temp.html");
                await File.WriteAllTextAsync(isWritten, html);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isWritten;
        }


        public string ConvertHtmlContentToPdf(string url)
        {
            string pdfOutputPath = Path.Combine(_hostEnvironment.ContentRootPath, "temp.pdf");
            var cmdParam = $"--footer-right [page]/[topage] --enable-local-file-access  --encoding utf-8  -O Landscape \"{url}\"  \"{pdfOutputPath}\" ";

            string wkhtmltopdfPath = GetWkhtmltopdfExePath();
            if (!IsWkhtmltopdfInstalled())
            {
                throw new FileNotFoundException("wkhtmltopdf.exe not found.");
            }
            var startInfo = new ProcessStartInfo
            {
                FileName = wkhtmltopdfPath,
                Arguments = cmdParam,
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };


            try
            {
                using var process = new Process { StartInfo = startInfo };
                process.Start();



                //byte[] pdfBytes = File.ReadAllBytes(pdfOutputPath);


                //var base64String = Convert.ToBase64String(pdfBytes.ToArray());

                //return $"data:{PdfContentType};base64,{base64String}";
                return "OK";
            }
            catch (Exception ex)
            {

                throw;
            }
        }



    }
}
